//
//  NetworkTools.swift
//  JIMWeiBo
//
//  Created by 陈恒均 on 2018/2/10.
//  Copyright © 2018年 陈恒均. All rights reserved.
//

import AFNetworking
enum RequestType : String {
    case GET = "GET"
    case POST = "POST"
}

class NetworkTools: AFHTTPSessionManager {
    //单例
    static let shareInstance : NetworkTools = {
        let tools = NetworkTools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/text/plain")
        
        return tools
    }()
}

// MARK:- 封装请求方法
extension NetworkTools
{
    func request(methodType:RequestType , urlstring : String , parameters:[String:Any] , finished:@escaping (_ result:Any? , _ error:Error?)->()) {

        let successCallBack = {(task :URLSessionDataTask, result : Any) in
            finished(result as AnyObject?, nil)
        }
        // 2 失败回调
        let failureCallBack = {(task : URLSessionDataTask?, error :Error) in
            finished(nil, error )
        }
        
        if methodType == .GET {
            // get请求
            
            get(urlstring, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
        }else {
            // post请求
            
            post(urlstring, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
            
        }
        
        
    }
}
// MARK:- 请求AccessToken
extension NetworkTools
{
    func loadAccessToken(code:String ,finished:@escaping (_ result:[String : Any]? , _ error:Error?) -> ()) {
        let urlString = "https://api.weibo.com/oauth2/access_token"

        let parmeters = ["client_id" : app_key, "client_secret" : app_secret, "grant_type" : "authorization_code", "redirect_uri" : redirect_uri, "code" : code]
        
        request(methodType:.POST, urlstring: urlString, parameters: parmeters) { (result, error) in
//            print(result as Any)
            finished(result as? [String : Any], error)
        }
 
    }
}
//请求用户数据
extension NetworkTools
{
    func loadUserInfo(access_token : String, uid : String,finished:@escaping (_ result:[String : Any]? , _ error:Error?) -> ()) {
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let parameters = ["access_token" : access_token, "uid" : uid]
        
        request(methodType: .GET, urlstring: urlString, parameters:parameters) { (result, error) in
//            print(result as Any)
            
            finished(result as? [String : Any],error)
        }
    }
   
    
    
}

// MARK:- 请求首页数据
extension NetworkTools{
    func loadStatuses(since_id : String? ,max_id : String? , finish:@escaping (_ result:[[String :Any]]? , _ error : Error?)->())  {
        let urlString =  "https://api.weibo.com/2/statuses/home_timeline.json"
        let access_token = (UserAccountViewModel.shareInstance.account?.access_token)!
        
        var parameters = ["access_token" :access_token]
        if let since_id = since_id {
            parameters = ["access_token" :access_token ,"since_id" : since_id]
        }
        
        if let max_id = max_id {
            parameters = ["access_token" :access_token ,"max_id" : max_id]
        }
        
     
        request(methodType: .GET, urlstring: urlString, parameters: parameters) { (result, error) in
//            print(result as Any)
            guard let resultDict = result as? [String : Any] else
            {
                
                finish(nil, error)
                return
            }
            
//            print(result!)
            finish(resultDict["statuses"] as? [[String :Any]] ,error)
 
        }
    
    }
}
// MARK:- 发送微博
extension NetworkTools{
    func sendStatus(status : String , isSuccess : @escaping (_ isSuccess : Bool) -> ()) {
        let urlString = "https://api.weibo.com/2/statuses/upload.json"
        let access_token = (UserAccountViewModel.shareInstance.account?.access_token)!
        let parmeters = ["access_token" : access_token, "status" : status]
        request(methodType: .POST, urlstring: urlString, parameters: parmeters) { (result, error) in
            if result != nil{
                isSuccess(true)
            }else{
                isSuccess(false)
            }
            
        }
    
    }
}

//发送微博并且携带照片
extension NetworkTools{
    func sendStatues(status : String ,image : UIImage, isSuccess : @escaping (_ isSuccess : Bool) -> ())  {
        
        let urlString = "https://api.weibo.com/2/statuses/share.json"
        let access_token = (UserAccountViewModel.shareInstance.account?.access_token)!
        let parmeters = ["access_token" : access_token, "status" : status]
        
        post(urlString, parameters: parmeters, constructingBodyWith: { (formData) in  
            if let imageData = UIImageJPEGRepresentation(image, 0.5){
                formData.appendPart(withFileData: imageData, name: "pic", fileName: "123.png", mimeType: "image/png")
            }
        }, progress: nil, success: { (_, _) in
            isSuccess(true)
        }) { (_, error) in
            print(error)
        }
        
    }
}



